<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use QL\QueryList;
use Curl\MultiCurl;

class Index extends Controller
{
    public function test(){

         return $this->fetch('base');
    }

    /*
     *search()  网站搜索页面,显示起点24小时排行榜
     */
    public function index(){
        $page = $this->request->param('page');

        $ql = QueryList::run('Request',[
            'target' => 'http://r.qidian.com/hotsales',
            'method' => 'GET',
            'params' => ['page'=>$page],
            'user_agent'=>'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0',
            //等等其它http相关参数，具体可查看Http类源码
        ]);
        $data = $ql->setQuery(array(
            'name'=>array('.book-mid-info>h4>a','text'),
            'author'=>array('.author>.name','text'),
            'link'=>array('.book-mid-info>h4>a','href'),
            'update'=>array('.update>a','text')
        ))->data;

        $page = ($page<=25 && $page>0)?$page:1;
        $this->assign('page',$page);
        $this->assign('data',$data);
        return $this->fetch('index');
    }

    /*
     * queryListQidian() 获取起点搜索结果
     * $book    书名
     * $page    起点搜索页数
     * return   以json形式，返回正确的10个搜索结果
     */
    public function queryListQidian(){
        $book = $this->request->param('book');
        $page = $this->request->param('page');

        $data = self::crawlerQidian($book,$page);
        $this->assign('data',$data);
        return $this->fetch('queryListQidian');
    }


    /*
     * queryListBaidu() 获取百度搜索结果（已去除包含百度网址的网站）+筛选拥有最新章节的
     * $book    书名
     * $link  起点链接
     * $page    代表上一次匹配百度搜索结果的第几页
     * return   只截取正确的搜索结果
     */
    public function queryListBaidu(){
        ini_set('max_execution_time', 0); 
        $book = $this->request->param('book');
        $link = $this->request->param('link');
        $page = $this->request->param('page');

        $update = self::findUpdate($link);
        
        // do{
        //     $links = self::crawlerBaidu($book,$page);
        //     $i=0;
        //     foreach ($links as $value){
        //         if(($lk=self::matching($value['link'],$update))==null){
                    //     unset($links[$k]);
                    // }

        //         $i++;
        //         if ($i==10)break 2;
        //     }
        //     $page++;
        // }while(1);

        $links = self::crawlerBaidu($book,$page);
        foreach ($links as $k=>$value){
            $lk=self::matching($value['link'],$update);
            if($lk==null){
                unset($links[$k]);
            }
        }
        
        $links = array_filter($links);
        $this->assign('data',$links);
        return $this->fetch('queryListBaidu');
    }





    /*
    * queryListQidian() 获取起点搜索结果
    * $book    书名
    * $page    起点搜索页数
    * return   以json形式，返回正确的10个搜索结果
    */
    public static function crawlerQidian($book,$page=null){
        $ql = QueryList::run('Request',[
            'target' => 'http://se.qidian.com',
            'method' => 'GET',
            'params' => ['kw'=>$book,'page'=>$page],
            'user_agent'=>'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0',
            //等等其它http相关参数，具体可查看Http类源码
        ]);
        $data = $ql->setQuery(array(
            'name'=>array('.book-mid-info>h4>a','text'),
            'author'=>array('.author>.name','text'),
            'link'=>array('.book-mid-info>h4>a','href'),
            'update'=>array('.update>a','text')
        ))->data;

        //输出结果：二维关联数组
        return $data;
    }


    /*
    * queryListBaidu() 获取百度搜索结果（已去除包含百度网址的网站）
    * $book    书名
    * $page    百度搜索页数
    * return   只截取正确的10个搜索结果
    */
    public static function crawlerBaidu($book,$page=null){
        $page = ($page-1)*10;//百度分页是这样的啦

        $ql = QueryList::run('Request',[
            'target' => 'http://www.baidu.com/s',
            'method' => 'GET',
            'params' => ['wd'=>"\"$book\" -(site:baidu.com)",'pn'=>$page],
            'user_agent'=>'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0',
            //等等其它http相关参数，具体可查看Http类源码
        ]);

        $data = $ql->setQuery(array(
            'name'=>array('h3>a','text'),
            'link'=>array('h3.t>a','href')
        ))->data;

        $data = array_slice($data,0,10,true);
        return $data;
    }

    /*
    * matching() 匹配百度搜索的网址里面有没有最新章节
    * $link    crawlerBaidu函数返回的网页链接数组
    * $word    查找的关键词
    * return   返回拥有关键词的网页链接
    */
    public static function matching($url,$words){
        stream_context_set_default(array('http' => array('method' => 'HEAD',)));
        @$headers = get_headers(trim($url), 1);

        if(is_array($headers['Location'])){
            $link = $headers['Location'][0];
        }else{
            $link = $headers['Location'];
        }

        $ch = curl_init();
        $this_header = array(
        "content-type: application/x-www-form-urlencoded; 
        charset=UTF-8"
        );

        curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header);
        curl_setopt($ch, CURLOPT_URL, $link);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    //  抓取URL
        $content = curl_exec($ch);

    //   关闭cURL资源，并且释放系统资源
        curl_close($ch);

        // $content = mb_convert_encoding($content,'utf-8');
//        $result = mb_stristr($content,$words);
        //  $content = iconv('GBK','utf-8//IGNORE',$content);
        //  $result = preg_match("/$words/",$content);
        $result = stripos($content,$words);

        if($result!=false){
            return $link;
        }
        return null;
    }

    /*
    * 起点搜索页面，小说最新章节不准，传入小说链接，获取小说最新章节
    * $link    链接
    * return   返回最新章节名
    */
    public static function findUpdate($link){
        
        if (strpos($link,'http')!==false){
            $ql = QueryList::run('Request',[
            'target' => $link.'#Catalog',
            'method' => 'GET',
            'params' => [],
            'user_agent'=>'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0',
            //等等其它http相关参数，具体可查看Http类源码
        ]);
        }else {
            $ql = QueryList::run('Request',[
            'target' => 'http:'.$link.'#Catalog',
            'method' => 'GET',
            'params' => [],
            'user_agent'=>'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0',
            //等等其它http相关参数，具体可查看Http类源码
            ]);
        }
        
        
        $data = $ql->setQuery(array(
//            'update'=>array('.volume ul.cf li a','text'),
            'update'=>array('div.book-state ul li a.blue','text')
        ))->data;

        $update = end($data)['update'];


        return $update;
    }
}